// +--------------------------------------------------------------------------
// | 轮播图管理路由控制器
// +--------------------------------------------------------------------------

const express = require("express");
const fs = require("fs");

const router = express.Router();

const config = require("../../config/config");
const { multer } = require("../../model/tools");
const FocusModel = require("../../model/focusModel");
const { error } = require("console");

router.get("/", async (req, res) => {
    const result = await FocusModel.find({});
    res.render("admin/focus/index.html", { list: result });
})

router.get("/add", (req, res) => {
    res.render("admin/focus/add.html");
});

router.post("/doAdd", multer().single("focus_img"), async (req, res) => {
    // static\\upload\\20250803\\1754231268710.png
    let focus_img = req.file?.path.substr(7) || "";
    const result = new FocusModel(Object.assign(req.body, { focus_img }));
    await result.save();
    res.redirect(`/${config.adminPath}/focus`);
});

router.get("/edit", async (req, res) => {
    const id = req.query.id;
    const result = await FocusModel.find({ _id: id });
    res.render("admin/focus/edit.html", { list: result[0] });
});

router.post("/doEdit", multer().single("focus_img"), async (req, res) => {
    try {
        if(req.file) {
            // 更新了图片
            let focus_img = req.file?.path.substr(7) || "";
            await FocusModel.updateOne({ _id: req.body.id }, Object.assign(req.body, { focus_img }));
        } else {
            await FocusModel.updateOne({ _id: req.body.id }, req.body);
        }
        res.redirect(`/${config.adminPath}/focus`);
    } catch (error) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${config.adminPath}/focus/edit?id=${req.body.id}`,
            "message": "修改数据失败"
        });
    }
});

router.get("/delete", async (req, res) => {
    try {
        const resultList = await FocusModel.find({ _id: req.query.id });
        const delResult = await FocusModel.deleteOne({ _id: req.query.id });
        if(delResult.ok == 1 && delResult.n == 1) {
            fs.unlink("static/"+resultList[0].focus_img, (error) => {
                console.log(`error`, error);
            })
        }
        res.render("admin/public/success.html", {
            "redirectUrl": `/${config.adminPath}/focus`,
            "message": "删除数据成功"
        });
    } catch (error) {
        res.render("admin/public/error.html", {
            "redirectUrl": `/${config.adminPath}/focus`,
            "message": "修改数据失败"
        });
    }
});

module.exports = router